package com.goodfox.web.generic.login.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.authority.entity.Resources;
import com.goodfox.web.generic.authority.service.ResourcesService;
import com.goodfox.web.generic.function.entity.Function;
import com.goodfox.web.generic.function.service.FunctionService;
import com.goodfox.web.generic.login.entity.LoginLog;
import com.goodfox.web.generic.login.service.LoginService;
import com.goodfox.web.generic.organization.service.OrganizationService;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.service.GradeService;

/**
 * 登录Controller
 * @author qin gt
 * 
 */
@Controller
@RequestMapping("/login")
public class LoginController{

	/** log4j日志器 */
	private Logger logger = Logger.getLogger(LoginController.class);

	/** 资源Service */
	@Autowired
	private ResourcesService resourcesService;

	/** 登录Service */
	@Autowired
	private LoginService loginService;
	
	/** 组织机构Service */
	@Autowired
	private OrganizationService organizationService;
	
	@Autowired
	private FunctionService functionService;
	
	@Autowired
	private GradeService gradeService;
	
	@Autowired
	private EntityService entityService;
	
	/**
	 * 访问登录action
	 * @return 登录页面
	 */
	@RequestMapping(value = "login.shtml")
	public String login(HttpServletRequest request,HttpServletResponse response) {
		logger.info("进入登录页");
		if("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null){ 
			try{
				ObjectMapper om=new ObjectMapper();
				Map rspMap=new HashMap();
				rspMap.put("statusCode", "301");
				rspMap.put("message", "登录超时，请重新登录！");
				String responseJson = om.writeValueAsString(rspMap);
				response.getWriter().write(responseJson);
			}catch(Exception ex){
				logger.error("进入登录页异常：",ex);
			}
			return null;
		}else{       
			return "login/login"; 
		}
	}
	
	/**
	 * 登录成功action
	 * @param request
	 * @param model
	 * @return 系统主页面
	 */
	@RequestMapping(value = "loginSuccess.shtml")
	public String loginSuccess(HttpServletRequest request, ModelMap model) {
		try {
			HttpSession session=request.getSession(false);
			if(session!=null)
			{
				session.removeAttribute("__flexSession");
			}
			//获取spring security上下文
			SecurityContextImpl securityContext=(SecurityContextImpl)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			//获取登录账户实体
			Account loginAccount=(Account)securityContext.getAuthentication().getPrincipal();

			model.addAttribute("loginAccount", loginAccount);
			//获取账户拥有资源
			Set<Resources> haveResourcesSet = resourcesService.queryResourcesSetByRoleId(loginAccount.getRoleId());
			//资源与账户绑定
			loginAccount.setResourcelSet(haveResourcesSet);
			
			//获取功能菜单列表
			Set<Function> menuFunSet=functionService.queryMenuFunSetByRoleId(loginAccount.getRoleId());
			//将菜单列表推送到前台页面
			model.addAttribute("menuFunSet", menuFunSet);
			
			//账户信息存入session
			request.getSession().setAttribute("loginAccount", loginAccount);
			
			loginAccount.setActOrganization(organizationService.getOrganization(loginAccount.getOrgId()));

			//设置参数
			Map map = new HashMap();
			map.put("actId", loginAccount.getActId());
			map.put("lgnIp", request.getLocalAddr());
			LoginLog loginLog=(LoginLog)entityService.fillEntity(map, LoginLog.class);
			
			//登录系统成功
			request.getSession().setAttribute("loginLogId", loginService.loginSuccess(loginLog));
			logger.info("登录成功："+request.getSession().getAttribute("loginLogId"));
			return "login/main";
		} catch (Exception ex) {
			logger.error("进入主页面异常：", ex);
			return "login/login";
		}
	}
	
	/**
	 * 登录失败action
	 * @param request
	 * @param model
	 * @return 登录页面
	 */
	@RequestMapping(value = "loginFailure.shtml")
	public String loginFailure(HttpServletRequest request, ModelMap model) {
		try {
			String actId=loginService.checkLoginAccount(request.getSession().getAttribute("SPRING_SECURITY_LAST_USERNAME").toString());
			if(actId==null){
				logger.debug("登录失败：用户名不存在");
				model.put("errorMsg", "用户名不存在");
			}else{
				Map map = new HashMap();
				map.put("actId", actId);
				map.put("lgnIp", request.getLocalAddr());
				LoginLog loginLog=(LoginLog)entityService.fillEntity(map, LoginLog.class);
				loginService.loginFailure(loginLog);
				logger.debug("登录失败：密码错误");
				model.put("errorMsg", "密码错误");
			}
		} catch (Exception ex) {
			logger.error("登录失败异常：", ex);
		}
		return "login/login";
	}
	
	/**
	 * 登出系统action
	 * @param request
	 * @return 登录页面
	 */
	@RequestMapping(value = "logout.shtml")
	public String logout(HttpServletRequest request) {
		try{
			Map map = new HashMap();
			Account loginAccount=(Account)request.getSession().getAttribute("loginAccount");
			map.put("actId", loginAccount.getActId());
			map.put("lgnIp", request.getLocalAddr());
			loginService.logoutSuccess(map);
			
			HttpSession session=request.getSession(false);
			if(session!=null){
				session.removeAttribute("__flexSession");
				session.removeAttribute("loginAccount");
			}
		}catch(Exception ex){
			logger.error("登出系统异常：",ex);
		}
		return "redirect:/j_spring_security_logout";
	}
	
	/**
	 * 登录超时action
	 * @param request
	 * @return 登录页面
	 */
	@RequestMapping(value = "timeout.shtml")
	public String timeout(HttpServletRequest request) {
		try{
			HttpSession session=request.getSession(false);
			if(session!=null){
				session.removeAttribute("__flexSession");
				session.removeAttribute("loginAccount");
			}
		}catch(Exception ex){
			logger.error("登录超时异常：",ex);
		}
		return "redirect:/login/login.shtml";
	}
}
